/*
 * @lc app=leetcode.cn id=606 lang=cpp
 *
 * [606] 根据二叉树创建字符串
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution
{
    string ans;
    void find(TreeNode *root)
    {
        ans += to_string(root->val);
        if (root->left && root->right)
        {
            ans += '(';
            find(root->left);
            ans += ")(";

            find(root->right);
            ans += ')';
        }
        else if (root->left)
        {
            ans += '(';
            find(root->left);
            ans += ')';
        }
        else if (root->right)
        {
            ans += "()(";
            find(root->right);
            ans += ')';
        }
        return;
    }

public:
    string tree2str(TreeNode *root)
    {
        if (!root)
            return "";
        find(root);
        return ans;
    }
};
// @lc code=end
